package com.jyhs.maven.service.impl;


import com.jyhs.maven.dao.TransferDao;
import com.jyhs.maven.dao.UserDao;
import com.jyhs.maven.dao.impl.UserDaoImpl;
import com.jyhs.maven.entity.Transfer;
import com.jyhs.maven.entity.User;
import com.jyhs.maven.entity.dto.TransferRecord;
import com.jyhs.maven.entity.dto.TransferRecordQuery;
import com.jyhs.maven.service.TransferService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

@Service("transferServiceImpl")
public class TransferServiceImpl implements TransferService {

//    TransferDao transferDao = TransferDaoFactory.getInstance();

    @Value("${resp.success.msg}")
    private String returnMsg;

    @Resource
    TransferDao transferDao;

    public void setTransferDao(TransferDao transferDao) {
        this.transferDao = transferDao;
    }

    @Resource
    UserDao userDao;
    @Override
    @Transactional
    public int saveTransfer(Transfer transfer) throws SQLException, ClassNotFoundException {

        //先判断余额是否足够
        User user = userDao.getUser(transfer.getPayUserId());
        if (user.getBalance().compareTo(transfer.getBalance())>0){

            // 1、付款人减少余额
            transferDao.updateAmount(transfer.getPayUserId(),transfer.getBalance());

            // 2、收款人增加余额
            transferDao.updateAmount(transfer.getReciveUserId(),transfer.getBalance().negate());

            //1.2 保存操作日志
            saveLog();

            int i = 1/0;
            // 3、保存转账记录
            transferDao.saveTransfer(transfer);
            return 1;
        }
        return 0;

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveLog() {
        System.out.println("保存日志到数据库1");
        System.out.println("保存日志到数据库2");
        System.out.println("保存日志到数据库3");
    }

    @Override
    public List<TransferRecord> getTransferList(TransferRecordQuery query) throws SQLException, ClassNotFoundException, ParseException, IllegalAccessException {
        return transferDao.getTransferList(query);
    }

    @Override
    public int getTransferCount(TransferRecordQuery query) throws SQLException, ClassNotFoundException {
        return transferDao.getTransferCount(query);
    }
}
